define(function (require, exports, module) {

    require("apps/best/page.css");
    require("apps/grid");
    require("apps/easyui");

    var comp = require("apps/lab/components");
    var filedComponent = comp.components;

    exports.init = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid);
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                myToolbar: "nsdb",
                colbar: "colbar"
            },
            configs: {
                gridUrl: ctx + "/app/api/best/recordList",
                idField: "id",
                gridColumns: [
                    {
                        field: 'id',
                        checkbox: true
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'tProcessTemplate.processName',
                        title: '工艺',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'reason',
                        title: '推荐原因',
                        width: 300,
                        align: 'left'
                    },
                    {
                        field: 'remark',
                        title: '备注',
                        width: 100,
                        hidden: true,
                        align: 'left'
                    },
                    {
                        field: 'createTime',
                        title: '创建时间',
                        width: 100,
                        align: 'left'
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "update":
                            whenUpdate(context, btn.href, row);
                            break;
                        default :
                            break;
                    }
                },
                onClickToolbarBtn: function (context, btn) {
                    switch (btn.key) {
                        case "search_all":
                            context.searchAll();
                            break;
                        case "search":
                            context.search(btn.href, "最优流程搜索", "best_record_search");
                            break;
                        case "del":
                            context.del(btn.href);
                            break;
                        case "add":
                            whenAdd(context, btn.href);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        var globalWindow = new $.PageWindow();

        function whenView(context, row) {
            globalWindow.create({
                width: 700,
                href: ctx + "/app/api/lab/view?id=" + row.id,
                title: "最优参数"
            });
            globalWindow.open();
        }

        function whenAdd(context, href) {
            globalWindow.create({
                href: href,
                title: "新增最优参数",
                method: "addBestRecord",
                width: 1000,
                callback: function (status) {
                    if (status) {
                        context.grid.datagrid("reload")
                    }
                }
            });
            globalWindow.open();
        }
        var processTools = null;
        function getProcessTool(){
            if(!processTools){
                $.ajax({
                    async:false,
                    url:ctx + "/app/api/directory/list",
                    data:{dirGroup: "DIRECTORY_PROCESS_TOOL"},
                    type:"GET",
                    dataType:"JSON",
                    success:function(data){
                        var content = data.content;
                        var options = content.map(function (item) {
                            return "<option value=\"" + item.dirValue + "\">" + item.dirValue + "</option>";
                        });
                        processTools  = options.join("");
                    }
                });
            }return processTools;
        }

        var templateForDialog = '<div class="input-250"><div class="box_tc_s"><input type="hidden" data-id="id" name="id" value="{{id}}" />' +
            '<table border="1" cellpadding="0" cellspacing="0" class="hydra-table">' +
            '{{#attrParams}}<tr class="hydra-tr-bg"><td class="hydra-left">{{fieldName}}</td>' +
            '<td class="hydra-right"><input type="hidden" value="{{fieldName}}" name="fieldName" />' +
            '<input type="hidden" value="{{unit}}" name="unit" /><input type="hidden" value="{{fieldType}}" name="fieldType" />' +
            '<input type="hidden" value="{{orderNo}}" name="orderNo" />' +
            '<span data-id="component">组件加载中</span>{{unit}}{{#useDevice}}' +
            '<span data-device-value="{{parameterDevice}}" class="ml10">测量工具：</span>' +
            '<select data-id="device" name="parameterDevice" class="hydra-input-width" style="width: 100px;"></select>{{/useDevice}}' +
            '</td></tr>{{/attrParams}}</table></div></div>';

        function whenUpdate(context, href, row) {
            $.getJSON(ctx + "/app/api/lab/record", {id:row.id}, function(data){
                var processName = data.tProcessTemplate.processName, values = data.tProcessParameters, attrParams = data.tProcessTemplate.tProcessAttributes;
                var uuid = $.utils.createUUID(12);
                for(var i= 0, l = attrParams.length; i < l; i++){
                    for(var j= 0, ll = values.length; j < ll; j++){
                        if (attrParams[i].fieldName == values[j].fieldName) {
                            attrParams[i].parameterValue = values[j].parameterValue;
                            attrParams[i].unit = (values[j].unit == "无" || !values[j].unit) ? "" : values[j].unit;
                            attrParams[i].parameterDevice = values[j].parameterDevice;
                            break;
                        }
                    }
                }
                var panel = $(Mustache.render(templateForDialog, {id:row.id, attrParams:attrParams})).appendTo("body").attr("id", uuid);
                panel.find("[data-id=device]").each(function(){
                    $(this).html(getProcessTool()).combobox({editable: false});
                    var v = $(this).prev().attr("data-device-value");
                    $(this).combobox("select", v);
                });
                panel.find("[data-id=component]").each(function (i) {
                    filedComponent[attrParams[i].fieldType].call(this, ctx, $.extend({name: "parameterValue"}, attrParams[i]), attrParams[i].parameterValue);
                });
                panel.dialog({
                    width: 600,
                    height: 500,
                    modal: true,
                    closable: true,
                    loadingMessage: '页面加载中，请稍后...',
                    title: "修改" + processName + "参数",
                    onClose: function () {
                        panel.dialog("destroy");
                        panel.remove()
                    },
                    buttons: [
                        {
                            text: "确认",
                            handler: function () {
                                var tProcessParameters = [];
                                panel.find("tr.hydra-tr-bg").each(function () {
                                    var params = $(this).serializeJson();
                                    if(params.fieldType == 'FIELD_TYPE_TABLE'){
                                        params.parameterValue = $(this).find("[data-id=f-component]").prop("outerHTML");
                                    }
                                    tProcessParameters.push(params);
                                });
                                $.post(ctx + "/app/api/best/updateRecord", $.utils.buildJson({id:panel.find("[data-id=id]").val(),
                                    tProcessParameters:tProcessParameters}), function(json){
                                    if ($.isErrorRequest(json)) {
                                        $.messager.alert('信息', json.msg, 'info');
                                    } else {
                                        $.messager.alert('信息', '修改成功', 'info');
                                        panel.dialog("close");
                                        panel.dialog("destroy");
                                        panel.remove();
                                    }
                                }, "JSON");
                            }
                        },
                        {
                            text: "关闭",
                            handler: function () {
                                panel.dialog("close");
                                panel.dialog("destroy");
                                panel.remove()
                            }
                        }
                    ]
                });
            });
        }
    };

    var typeValueSet = {
        FIELD_TYPE_TIME: function (input, value) {
            if (/\d{4}(-\d\d){2}(\S\d{2}(:\d\d){2})?/.test(value)) {
                input.datetimebox("setValue", value);
            } else {
                input.datetimebox("setValue", "");
            }
        },
        FIELD_TYPE_TEXTAREA: function (input, value) {
            input.val(value);
        },
        FIELD_TYPE_DIRECTORY: function (input, value) {
            input.combobox("select", value)
        },
        FIELD_TYPE_TEXT: function (input, value) {
            input.val(value);
        },
        FIELD_TYPE_NUM: function (input, value) {
            if (/[\+\-]?\d+.?\d*/.test(value)) {
                input.numberbox("setValue", value);
            } else {
                input.numberbox("setValue", "");
            }
        },
        FIELD_TYPE_ATTACHMENT: function (input, value) {
            input.removeAttr("data-name");
            input.val("");
            input.prev().empty();
            if (value && value.lastIndexOf(".") > -1) {
                input.fileupload("addFile", "", value);
            }
        },
        FIELD_TYPE_SCIENTIFIC: function (input, value) {
            if (/[\+\-]?\d+,\d+/.test(value)) {
                var vv = value.split(",");
                input.eq(0).numberbox("setValue", vv[0]);
                input.eq(1).numberbox("setValue", vv[1]);
            } else {
                input.numberbox("setValue", "");
            }
        },
        FIELD_TYPE_TABLE: function (input, value) {
            if (value) {
                input.replaceWith(value);
            }
        }
    };

    exports.add = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid);
        initSavePanel(ctx, page, uuid);
        window.addBestRecord = function (win) {
            if (!page.getJqDom("lab-item").filter(".clicked").length) {
                $.messager.alert("至少需要选择一个模板填写参数");
            }
            if (!page.getJqDom("parameterForm").form("validate")) {
                page.getJqDom("accordion").accordion("select", "填写工艺参数");
                return false;
            }
            if (!page.getJqDom("baseForm").form("validate")) {
                page.getJqDom("accordion").accordion("select", "填写工艺参数");
                return false;
            }
            var postData = page.getJqDom("baseForm").serializeJson();
            postData.tProcessParameters = [];
            page.getJqDom("parameter").find("tr.hydra-tr-bg").each(function () {
                var params = $(this).serializeJson();
                if (params.fieldType == 'FIELD_TYPE_TABLE') {
                    params.parameterValue = $(this).find("[data-id=f-component]").prop("outerHTML");
                }
                postData.tProcessParameters.push(params);
            });
            win.wait("start", "保存中,请稍候.");
            $.post(ctx + "/app/api/best/addRecord?random=" + Math.random(), $.utils.buildJson(postData),
                function (data) {
                    win.wait("end");
                    if ($.isPlainObject(data) && data.error) {
                        $.messager.alert('信息',
                            data.msg, 'error');
                    } else {
                        $.messager.alert('信息',
                            '保存最优参数成功', 'info');
                        win.callback(true);
                        win.close();
                    }
                }, "JSON");

        }
    };

    function initSavePanel(ctx, page, uuid){
        page.getJqDom("accordion").accordion().find(".panel-tool").hide();
        page.getJqDom("lab-item").on("click", function () {
            if (!$(this).hasClass("clicked")) {
                var href = $(this).attr("data-href");
                page.getJqDom("lab-item").removeClass("clicked");
                $(this).addClass("clicked");
                page.getJqDom("parameter").panel({
                    title: $(this).attr("data-title"),
                    href: href
                });
                var id = $(this).attr("data-process-id");
                page.getJqDom("tProcessTemplate").val(id);
                if ($(this).attr("data-record-total") != '0') {
                    page.getJqDom("same-ebom").show();
                    page.getJqDom("grid").datagrid("load", {"tProcessTemplate.id": id})
                } else {
                    page.getJqDom("same-ebom").hide();
                }
            }
            page.getJqDom("accordion").accordion("select", "填写工艺参数");
        });
        page.getJqDom("lab-title").each(function () {
            var h = $(this).html();
            h = h.length > 4 ? h.substr(0, 3) + "..." : h;
            $(this).html(h);
        });
        page.getJqDom("goToChooseProcess").linkbutton({
            onClick: function () {
                page.getJqDom("accordion").accordion("select", "选择工艺模板");
            }
        });
        var pageListComponent = new $.PageListComponent(uuid, {
            view: {
                grid: "grid",
                colbar: "user_list_btn"
            },
            configs: {
                gridUrl: ctx + "/app/api/lab/relative",

                idField: "id",
                gridColumns: [
                    {
                        field: 'id',
                        hidden: true,
                        checkbox: false
                    },
                    {
                        field: 'temp1',
                        hidden: true
                    },
                    {
                        field: 'operateTime',
                        title: '登记时间',
                        width: 100,
                        hidden: true,
                        align: 'left'
                    },
                    {
                        field: 'operator',
                        hidden: true,
                        title: '创建人',
                        width: 100,
                        align: 'left'
                    },
                    {
                        field: 'result',
                        title: '结果',
                        width: 100,
                        align: 'left'
                    }
                ]
            },
            events: {
                renderColBarBefore: function (key, row) {
                    return true;
                },
                onClickColBtn: function (context, btn, row) {
                    switch (btn.key) {
                        case "view":
                            whenView(context, row);
                            break;
                        case "use":
                            whenUse(context, row);
                            break;
                        default :
                            break;
                    }
                }
            }
        });

        function whenView(context, row) {
            context.detail("工艺设计结构详情查看", row);
        }

        var cacheInfo = {};

        function whenUse(context, row) {
            if (cacheInfo[row.id]) {
                useTo(cacheInfo[row.id]);
            } else {
                $.getJSON(ctx + "/app/api/lab/getRecordInfo", {id: row.id}, function (data) {
                    cacheInfo[row.id] = data;
                    useTo(data);
                });
            }
        }
        function useTo(data) {
            var per = data.tProcessParameters;
            if (per && per.length > 0) {
                page.getJqDom("table-form").find("input[name=fieldName]").each(function () {
                    var parentTr = $(this).closest("tr");
                    var name = $(this).val(), type = parentTr.find("[name=fieldType]").val();
                    for (var i = 0, l = per.length; i < l; i++) {
                        if (per[i].fieldName == name && per[i].fieldType == type) {
                            typeValueSet[type](parentTr.find("[data-id=f-component]"), per[i].parameterValue)
                            break;
                        }
                    }
                });
            }
        }
    }

    exports.search = function (ctx, uuid) {
        var page = new $.PageDomFactory(uuid, true);
        window.best_record_search = function (win) {
            win.wait("start", "搜索中,请稍候.");
            var form = page.getJqDom("search-form");
            var postData = form.serializeJson();
            win.callback(postData);
            win.close();
        }
    }
});